const getQueryStringByName = function (name: string) {
  var result = location.search.match(new RegExp('[?&]' + name + '=([^&]+)', 'i'))
  if (result == null || result.length < 1) {
    return ''
  }
  return result[1]
}

const transformData = function (data: any) {
  const params = new FormData()
  for (const item in data) {
    params.append(item, data[item])
  }
  return params
}

const DateFormat = function (date: any, fmt?: string) {
  fmt = fmt || 'yyyy-MM-dd hh:mm:ss'
  if (date === null || typeof date === 'undefined' || date === '') {
    return null
  } else {
    // 时间要转成obj，否则报错
    date = new Date(date)
  }
  var o: any = {
    'M+': date.getMonth() + 1, // 月
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
    }
  }
  return fmt
}

/**
 * 深拷贝对象
 * 将 source 拷贝到 dest 并返回
 * @param {object} source
 * @param {object} dest
 * @returns new object
 */
const deepCopy = (source: { [x: string]: any; hasOwnProperty: (arg0: string) => any }, dest: {}) => {
  const result = dest || {}
  for (const i in source) {
    if (Object.prototype.hasOwnProperty.call(source, i)) {
      if (typeof source[i] === 'object' && source[i] !== null) {
        result[i] = source[i].constructor === Array ? [] : {}
        deepCopy(source[i], result[i])
      } else {
        result[i] = source[i]
      }
    }
  }
  return result
}

/**
 * 防抖
 * demo：debounce(func, 300)(args)
 * @param {Function} func 执行函数
 * @param {Number} wait 节流时间,毫秒
 * @return {Function} delay
 */
let timeout: NodeJS.Timer | null = null

const debounce = (func: Function, wait: number) => {
  const delay = function () {
    const args = arguments

    if (timeout) clearTimeout(timeout)

    timeout = setTimeout(() => {
      func.apply(delay, args)
    }, wait)
  }
  return delay
}

/**
 * 节流
 * demo：throttle(func, 300)(args)
 * @param {Object|Array} func 执行函数
 * @param {Number} wait 节流时间,毫秒
 * @return {Function} delay
 */
let previous = 0
const throttle = (func: Function, wait: number) => {
  const delay = function () {
    const now = Date.now()
    if (now - previous > wait) {
      func.apply(delay, arguments)
      previous = now
    }
  }
  return delay
}

export { getQueryStringByName, transformData, DateFormat, deepCopy, debounce, throttle }
